/**
 * @description 拖拽指令 v-drag 用于实现元素的拖拽功能 拖拽边界判定 限制拖拽范围 pc手机端拖拽
 */

const dragDirective = {
  mounted(el) {
    const header = el.querySelector(".drag-header");
    header.style.cursor = "move";
    el.style.position = "absolute";
    el.style.zIndex = 99999;

    const handleMouseDown = event => {
      const startX = event.clientX || event.touches[0].clientX;
      const startY = event.clientY || event.touches[0].clientY;
      const { left, top } = el.getBoundingClientRect();

      const handleMouseMove = moveEvent => {
        const moveX =
          (moveEvent.clientX || moveEvent.touches[0].clientX) - startX;
        const moveY =
          (moveEvent.clientY || moveEvent.touches[0].clientY) - startY;

        const newLeft = Math.max(
          0,
          Math.min(left + moveX, window.innerWidth - el.offsetWidth)
        );
        const newTop = Math.max(
          0,
          Math.min(top + moveY, window.innerHeight - el.offsetHeight)
        );

        el.style.left = `${newLeft}px`;
        el.style.top = `${newTop}px`;
      };

      const handleMouseUp = () => {
        window.removeEventListener("mousemove", handleMouseMove);
        window.removeEventListener("mouseup", handleMouseUp);
        window.removeEventListener("touchmove", handleMouseMove);
        window.removeEventListener("touchend", handleMouseUp);
      };

      window.addEventListener("mousemove", handleMouseMove);
      window.addEventListener("mouseup", handleMouseUp);
      el.addEventListener("touchmove", handleMouseMove);
      el.addEventListener("touchend", handleMouseUp);
    };

    header.addEventListener("mousedown", handleMouseDown);
    header.addEventListener("touchstart", handleMouseDown);
  },
  unmounted(el, binding, vnode) {
    console.log("unmounted__________", el, binding, vnode);

    el.style.position = "static";
  }
};

export default dragDirective;
